package com.bstek.bdf4.mybatis.autoconfigure;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.bstek.bdf4.utils.IdGenerator;
import com.bstek.bdf4.mybatis.core.encrypt.AESEncryptService;
import com.bstek.bdf4.mybatis.core.encrypt.Base64EncryptService;
import com.bstek.bdf4.mybatis.core.encrypt.EncryptService;
import com.bstek.bdf4.mybatis.core.enums.Algorithm;
import com.bstek.bdf4.mybatis.core.handlers.DefaultDBFieldHandler;
import com.bstek.bdf4.mybatis.core.handlers.EncryptTypeHandler;
import com.bstek.bdf4.mybatis.core.prop.EncryptProperties;
import com.bstek.bdf4.mybatis.core.prop.IdProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @Description: MybatisPlus配置类
 * @Author: zxq
 * @Date: 2024/1/25 - 17:10
 */

@Slf4j
@Configuration
@EnableConfigurationProperties({EncryptProperties.class, IdProperties.class})
public class DoradoMybatisAutoConfiguration {
    @Resource
    private EncryptProperties encryptProperties;
    @Resource
    private IdProperties idProperties;


    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        log.info("----------------- MybatisPlus--------------------");
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        // 分页插件
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return mybatisPlusInterceptor;
    }

    @Bean
    public MetaObjectHandler defaultMetaObjectHandler(){
        return new DefaultDBFieldHandler();
    }

    @Bean
    public EncryptTypeHandler encryptTypeHandler() {
        return new EncryptTypeHandler();
    }

    @Bean
    @ConditionalOnMissingBean(EncryptService.class)
    public EncryptService encryptService() {
        Algorithm algorithm = encryptProperties.getAlgorithm();
        EncryptService encryptService;
        switch (algorithm) {
            case BASE64:
                encryptService =  new Base64EncryptService();
                break;
            case AES:
                encryptService = new AESEncryptService();
                break;
            default:
                encryptService =  null;
        }
        return encryptService;
    }

    @Bean
    @ConditionalOnMissingBean(IdGenerator.class)
    public IdGenerator idGenerator() {
        IdGenerator idGenerator = new IdGenerator(idProperties.getDatacenter(), idProperties.getWorker());
        return idGenerator;
    }
}
